<template>
  <div class="wrapper">
    <el-dialog
        v-model="visible"
        title="配送单明细"
        :width="'80%'"
        :align-center="true"
        @close="handleClose"
        :before-close="handleBeforeClose"
    >
      <template #default>
        <div class="card-wrapper">
          <el-row :gutter="20" class="full-width" style="margin-top: 10px">
            <el-col :span="7">
              <el-form-item label="货品名称">
                <el-input v-model="filters.productName" placeholder="请输入货品名称" class="full-width"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批次">
                <el-input v-model="filters.productBatch" placeholder="请输入批次" class="full-width"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="订单号" class="full-width">
                <el-input v-model="filters.orderNumber" placeholder="请输入订单号" class="full-width"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="full-width" label=" ">
                <el-button-group class="full-width">
                  <el-button icon="search" type="primary" plain @click="search" style="width: 10%"></el-button>
                  <el-button icon="refresh" @click="resetFilters" style="width: 10%"></el-button>
                </el-button-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider style="margin-top: -5px; margin-bottom: 10px"></el-divider>
          <el-table :data="details" border style="width: 100%; border-radius: 12px;"
                    :header-cell-style="{
                  fontWeight: 'bold',
                  textAlign: 'center',
                }"
                    :cell-style="{
                  textAlign: 'center',
                }"
          :row-class-name="tableRowClassName">
            <el-table-column fixed prop="deliveryDetailId" label="配送单明细ID" width="150"/>
            <el-table-column prop="orderId" label="订单编号" width="120"/>
            <el-table-column prop="productName" label="货品名称" width="120"/>
            <el-table-column prop="productBatch" label="货品批次" width="120"/>
            <el-table-column prop="type" label="类型" width="80"/>
            <el-table-column label="状态" width="120">
              <template v-slot="{ row }">
                <p>{{ row.state }}</p>
              </template>
            </el-table-column>
            <el-table-column label="重量" width="120">
              <template v-slot="{ row }">
                <p>{{ row.weight }}{{ row.weightUnit }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="destination" label="目的地" width="120"/>
            <el-table-column prop="transportDetailId" label="运输订单明细" width="120"/>
            <el-table-column prop="transportQuantity" label="商品数量" width="120"/>
            <el-table-column label="预计送达时间" width="180">
              <template v-slot="{ row }">
                <p>{{ formatDate(row.expectedDeliveryTime) }}</p>
              </template>
            </el-table-column>
            <el-table-column label="送达时间" width="180">
              <template v-slot="{ row }">
                <p>{{ formatDate(row.deliveryTime) }}</p>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template v-slot="{ row }">
                <p>{{ formatDate(row.generatedDate) }}</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button @click="handleBeforeClose(()=>visible = false)">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import { getDelivery } from '@/api/delivery/delivery.js';
import {ElMessage} from 'element-plus';

export default {
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    deliveryBatchId: {
      type: String,
      required: true
    }
  },
  setup(props, {emit}) {
    const visible = ref(props.modelValue);
    const details = ref([]);

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const fetchDetails = async () => {
      try {
        console.log('Fetching details for order:', props.deliveryBatchId);
        const response = await getDelivery(props.deliveryBatchId);
        console.log('Response:', response);
        details.value = response || [];
        console.log('Details:', details.value);
      } catch (error) {
        ElMessage.error('获取配送单明细失败');
        console.error(error);
      }
    };

    const handleBeforeClose = (done) => {
      emit('update:modelValue', false); // 关闭时触发更新父组件的状态
      done();
    };

    const handleClose = () => {
      visible.value = false;
    };

    const tableRowClassName = ({row, rowIndex}) => {
      if (row.state === 2) {
        return 'success-row';
      }
    };

    // Watcher for the visibility of the dialog
    watch(() => props.modelValue, (newVal) => {
      if (newVal) {
        fetchDetails();
      }
    });

    onMounted(() => {
      if (props.modelValue) {
        fetchDetails();
      }
    });

    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal;
      if (newVal) {
        fetchDetails();
      }
    });

    const filters = reactive({
      productName: '',
      productBatch: '',
      orderNumber: ''
    });

    const search = async () => {
      try {
        const response = await getDelivery(props.deliveryId, filters);
        details.value = response || [];
        console.log('Filtered details:', response);
      } catch (error) {
        ElMessage.error('获取配送单明细失败');
        console.error(error);
      }
    };

    const resetFilters = () => {
      filters.productName = '';
      filters.productBatch = '';
      filters.orderNumber = '';
      fetchDetails();
    };

    return {
      visible,
      details,
      formatDate,
      handleClose,
      handleBeforeClose,
      filters,
      search,
      resetFilters,
      tableRowClassName
    };
  }
};
</script>

<style scoped>
.card-wrapper {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  margin-top: 10px;
  padding-left: 14px;
  padding-right: 14px;
}

.wrapper:deep(.el-dialog) {
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 80vh;
  max-width: calc(100% - 30px);
  justify-content: space-between;
  padding: var(--el-dialog-padding-primary, 16px) 0;
  overflow: hidden;
}

.wrapper:deep(.el-dialog__header) {
  padding: 16px var(--el-dialog-padding-primary, 16px);
  padding-top: 8px;
}

.wrapper:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
}

.wrapper:deep(.el-dialog__footer) {
  padding: 0 var(--el-dialog-padding-primary, 16px);
  padding-top: 16px;
}

.card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  padding: 2px;
  margin-top: 10px;
}


.el-card {
  padding: 0;
}

.el-card:deep(.el-card__body) {
  padding: 0 !important;
}


.card-header {
  padding: 16px 5%;
  font-size: 14px;
  font-weight: bold;
  background-color: #f0f5ff;
  border-bottom: 1px solid #c8ddff;
}

.card-content {
  padding: 5%;
}

.el-card {
  width: calc(100% - 36px);
}

.card-content p {
  margin-bottom: 1px;
  font-size: 13px;
}

.card-content p strong {
  font-size: 13px;
  color: #333;
}

.el-row {
  margin-bottom: 2px;
}

.full-width {
  width: 100%;
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

</style>